<script setup lang="ts">
  import Pagination from '@/components/Pagination/index.vue'
  import { ref } from 'vue'
  import FormModal from './FormModal.vue'
  import {
    useWarrantyDel,
    useEnableWarrantyCategory,
    useDisableWarrantyCategory,
    useGetWarrantyCategoryList,
  } from './services'
  import { ElMessageBox, TableInstance } from 'element-plus'
  import { HMessage, HMessageBox } from '@/components/common/message'

  const { del } = useWarrantyDel()
  const { enable } = useEnableWarrantyCategory()
  const { disable } = useDisableWarrantyCategory()
  const { list, listTotal, getListLoading, getListParam, getList } = useGetWarrantyCategoryList()

  defineOptions({
    name: 'OrderWarrantyCategory',
  })

  // 分页组件实例
  const paginationInstance = ref<InstanceType<typeof Pagination> | null>(null)

  // 表单弹窗显示状态
  const formModalVisible = ref(false)

  // 正在编辑的类别id
  const editingWarrantyCategoryId = ref('')

  // 表格组件实例
  const tableInstance = ref<TableInstance | null>(null)

  // 质保类别选择列表
  const warrantyCategorySelectedList = ref<Array<OrderWarrantyCategoryItem>>([])

  /**
   * 获取列表
   */
  const _getList = () => {
    if (paginationInstance.value) {
      getListParam.value.page = paginationInstance.value.current
      getListParam.value.limit = paginationInstance.value.size
      getList()
    }
  }

  /**
   * 编辑事件
   * @param id - 类别id
   */
  const handleEdit = (id: string) => {
    editingWarrantyCategoryId.value = id
    formModalVisible.value = true
  }

  /**
   * 删除事件
   * @param warrantyCategory - 质保类别
   */
  const handleDel = (warrantyCategory: OrderWarrantyCategoryItem) => {
    if (tableInstance.value) {
      tableInstance.value.clearSelection()
      tableInstance.value.toggleRowSelection(warrantyCategory, true)
      ElMessageBox({
        title: '提示',
        type: 'error',
        message: '确定要删除该质保类别吗？',
        showCancelButton: true,
        autofocus: false,
        async beforeClose(action, instance, done) {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.cancelButtonLoading = true
            const res = await del(warrantyCategorySelectedList.value.map((item) => item.id))
            instance.confirmButtonLoading = false
            instance.cancelButtonLoading = false

            if (res.code === 20000) {
              HMessage.success('删除成功')
              done()
              _getList()
              return
            }

            HMessageBox.error(res.message)

            return
          }

          done()
        },
      })
    }
  }

  /**
   * 列表选择事件
   * @param warrantyCategoryList - 选择的质保类别
   */
  const handleSelectionChange = (warrantyCategoryList: Array<OrderWarrantyCategoryItem>) => {
    warrantyCategorySelectedList.value = warrantyCategoryList
  }

  /**
   * 批量操作
   * @param type - 操作类型
   */
  const handleMultipleOperate = (type: 'enable' | 'disable' | 'del') => {
    const message = {
      enable: '确定要启用选中的质保类别？',
      disable: '确定要禁用选中的质保类别？',
      del: '确定要删除选中的质保类别？',
    }

    const fn = {
      del: del,
      enable: enable,
      disable: disable,
    }

    const successMsg = {
      del: '删除成功',
      enable: '启用成功',
      disable: '禁用成功',
    }

    if (warrantyCategorySelectedList.value.length <= 0) {
      HMessageBox.error('请选择质保类别')
      return
    }

    ElMessageBox({
      title: '提示',
      type: type === 'del' ? 'error' : 'warning',
      message: message[type],
      showCancelButton: true,
      autofocus: false,
      async beforeClose(action, instance, done) {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.cancelButtonLoading = true
          const res = await fn[type](warrantyCategorySelectedList.value.map((item) => item.id))
          instance.confirmButtonLoading = false
          instance.cancelButtonLoading = false

          if (res.code === 20000) {
            HMessage.success(successMsg[type])
            done()
            _getList()
            return
          }

          HMessageBox.error(res.message)

          return
        }

        done()
      },
    })
  }

  defineExpose({
    getList: _getList,
  })
</script>

<template>
  <div v-loading="getListLoading" class="flex flex-column height-100 row-gap-5px">
    <header class="flex justify-space-between">
      <div class="flex column-gap-5px">
        <h-plain-button @click="formModalVisible = true">添加质保类别</h-plain-button>
        <el-dropdown trigger="click">
          <h-button :disabled="warrantyCategorySelectedList.length === 0">
            批量操作
            <el-icon>
              <ArrowDown />
            </el-icon>
          </h-button>

          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="handleMultipleOperate('enable')">启用</el-dropdown-item>
              <el-dropdown-item @click="handleMultipleOperate('disable')">禁用</el-dropdown-item>
              <el-dropdown-item @click="handleMultipleOperate('del')">删除</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      <div class="flex column-gap-5px">
        <div class="width-140px">
          <el-input
            v-model.trim="getListParam.name"
            placeholder="请输入关键字"
            clearable
            @keyup.enter="_getList"
            @clear="_getList"
          />
        </div>
        <h-button type="primary" @click="_getList">
          <el-icon>
            <Search />
          </el-icon>
          搜索
        </h-button>
      </div>
    </header>
    <main class="max-height-100-minus-66px">
      <el-table
        ref="tableInstance"
        :border="true"
        height="100%"
        :data="list"
        @selection-change="handleSelectionChange"
      >
        <!-- 序号 -->
        <el-table-column type="selection" width="50" :align="'center'" fixed="left" label="" />

        <!-- 序号 -->
        <el-table-column type="index" width="50" :align="'center'" fixed="left" label="序号" />

        <!-- 类别名称 -->
        <el-table-column label="质保类别名称" prop="name" min-width="140" show-overflow-tooltip />

        <!-- 是否收费 -->
        <el-table-column label="是否收费" width="100">
          <template #default="{ row }">{{ row.collectFee ? '是' : '否' }}</template>
        </el-table-column>

        <!-- 是否需要审核 -->
        <el-table-column label="是否需要审核" width="100">
          <template #default="{ row }">{{ row.checked ? '是' : '否' }}</template>
        </el-table-column>

        <!-- 是否为默认值 -->
        <el-table-column label="是否为默认值" width="100">
          <template #default="{ row }">{{ row.defaultSelect ? '是' : '否' }}</template>
        </el-table-column>

        <!-- 类别类型 -->
        <el-table-column label="质保类别类型" width="100">
          <template #default="{ row }">{{ row.type === 1 ? '保内' : '保外' }}</template>
        </el-table-column>

        <!-- 创建时间 -->
        <el-table-column label="创建时间" prop="createTime" width="140" />

        <!-- 创建时间 -->
        <el-table-column label="创建时间" prop="updateTime" width="140" />

        <!-- 状态 -->
        <el-table-column label="状态" fixed="right" :align="'center'" width="100">
          <template #default="{ row }">
            <div class="flex justify-center">
              <h-status v-if="!row.status">启用</h-status>
              <h-status v-else type="info">禁用</h-status>
            </div>
          </template>
        </el-table-column>

        <!-- 操作 -->
        <el-table-column label="操作" fixed="right" width="100">
          <template #default="{ row }">
            <h-space>
              <h-link @click="handleEdit(row.id)">编辑</h-link>
              <h-link type="error" @click="handleDel(row)">删除</h-link>
            </h-space>
          </template>
        </el-table-column>
      </el-table>
    </main>
    <footer class="flex justify-flex-end">
      <pagination
        ref="paginationInstance"
        :list_total="listTotal"
        @size-change="_getList"
        @current-change="_getList"
      />
    </footer>

    <form-modal
      v-model="formModalVisible"
      :warranty-category-id="editingWarrantyCategoryId"
      @update="_getList"
      @close="editingWarrantyCategoryId = ''"
    />
  </div>
</template>
